/**
 * AntDroid Copyright (c) 2008-2012 INRIA, University of Lille 1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 * Contact: nicolas.haderer@inria.fr
 *
 * Author: Haderer Nicolas
 */
package com.google.antranking.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class AtAsynchTask extends AsyncTask<Object, String,Object>{

	public interface IAtTask {
		public Object run(Object... result) throws Exception;
	}
	
	private IAtTask run;
	
	private ProgressDialog mProgressDialog;

	private Context mContext;
	
	private String message;
	
	private IAtTask onTaskFinish;
	
	private Object result;
	
	private Exception exception;
	
	public AtAsynchTask(IAtTask run, Context mContext, String message){
		this.run = run;
		this.mContext = mContext;
		this.message = message;
	}

	@Override
	protected String doInBackground(Object... args) {
		try {
			this.result = run.run(args);
		} catch (Exception e) {
			this.exception = e;
			e.printStackTrace();
		}
		
		return null;
	}
	
	protected void onProgressUpdate(Integer... progress) {}

	protected void onPostExecute(Object result) {
		mProgressDialog.dismiss();

		if (exception != null){
			AtUtils.showMessage(this.mContext, "Error : "+exception.getMessage());
		}
		else{

			if (onTaskFinish != null){
				
				try {
					onTaskFinish.run(this.result);
				} 
				catch (Exception e) {
					AtUtils.showMessage(this.mContext, "Error : "+e.getMessage());
					e.printStackTrace();
				}
			}
		}
	}
     
     public void run(Object... params){
    	 
    	mProgressDialog = new ProgressDialog(mContext);
 		mProgressDialog.setMessage(this.message);
 		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
 		mProgressDialog.setCancelable(false);
 		mProgressDialog.show();
    	this.execute(params);
     }

     public void setOnTaskFinished(IAtTask run){
    	 this.onTaskFinish = run;
     }
     
}
